﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Brc_PaaS.Common.Helper;
using Brc_PaaS.Common.Model.Basic;
using Brc_PaaS.Common.Model.RabbitMq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace Brc_PaaS.Core.RabbitMq
{
    public class RabbitMqListener : IHostedService
    {
        private readonly RabbitMQConnectionPool connectionPool;
        private readonly IConnection connection;
        protected string queueName;
        private IModel channel;

        public RabbitMqListener(IConfiguration configuration)
        {
            var entity = configuration.GetSection("RabbitMQSettingEntity").Get<RabbitMQSettingEntity>();
            connectionPool = new RabbitMQConnectionPool(entity);
            connection = connectionPool.CreateMQConnectionInPoolNew();
            channel = connection.CreateModel();
        }

        public BaseResponseModel Register()
        {
            BaseResponseModel result = new BaseResponseModel() { IsSuccess = false, Msg = string.Empty };

            channel.QueueDeclare(queueName, true, false, false);
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += ReceiveMessage;
            channel.BasicQos(0, 1, false);
            channel.BasicConsume(queue: queueName, consumer: consumer);
            result.IsSuccess = true;
            return result;
        }
        private void ReceiveMessage(object sender, BasicDeliverEventArgs e)
        {
            string json = Encoding.Default.GetString(e.Body);
            if (!json.StartsWith("{") && !json.StartsWith("["))
            {
                channel.BasicAck(e.DeliveryTag, false);
                return;
            }
            var eventMessage = JsonHelper.DeserializeObject<EventMessage>(json);
            var handerResult = Process(eventMessage);
            if (handerResult.IsSuccess)
            {
                channel.BasicAck(e.DeliveryTag, false);
            }
        }

        // 处理消息的方法
        public virtual BaseResponseModel Process(EventMessage eventMessage)
        {
            return new BaseResponseModel() { IsSuccess = true, Msg = string.Empty };
        }

        public void DeRegister()
        {
            connectionPool.ResetMQConnectionToFree(connection);
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            Register();
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            connectionPool.ResetMQConnectionToFree(connection);
            return Task.CompletedTask;
        }


    }
}
